<template>
  <div class="flex flex-1 gap-2">
    <!-- <div class="w-1/4">
      <ElderlyList :status="status" @handleElderlyCurrentChange="getElderlyInfo"/>
    </div> -->
    <div class="flex-1 flex flex-col gap-3 bg-white rounded-lg p-4">
      <!-- 顶部操作区 -->
      <div class="flex justify-between items-center">
        <div class="flex gap-4">
          <el-radio-group v-model="activeView" size="large">
            <el-radio-button :value="'group'">分群管理</el-radio-button>
            <el-radio-button :value="'campaign'">营销活动</el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button type="primary" @click="handleCreate">
            {{ activeView === 'group' ? '新建分群' : '新建活动' }}
          </el-button>
        </div>
      </div>

      <!-- 分群管理视图 -->
      <div v-if="activeView === 'group'" class="flex-1">
        <el-table :data="patientGroups" border stripe>
          <el-table-column type="index" label="序号" min-width="60" align="center" />
          <el-table-column prop="name" label="分群名称" min-width="150" />
          <el-table-column prop="count" label="人数" min-width="100">
            <template #default="{ row }">
              <el-tag :type="row.type">{{ row.count }}人</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="conditions" label="筛选条件" min-width="300">
            <template #default="{ row }">
              <el-tag
                v-for="(condition, index) in row.conditions"
                :key="index"
                class="mr-2"
                effect="plain"
              >
                {{ getConditionLabel(condition) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditGroup(row)">
                编辑
              </el-button>
              <el-button type="success" link @click="handleViewMembers(row)">
                查看成员
              </el-button>
              <el-button type="warning" link @click="handleDeleteGroup(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 营销活动视图 -->
      <div v-else class="flex-1">
        <el-table :data="marketingCampaigns" border stripe>
          <el-table-column type="index" label="序号" min-width="60" align="center" />
          <el-table-column prop="name" label="活动名称" min-width="100" />
          <el-table-column prop="type" label="活动类型" min-width="80">
            <template #default="{ row }">
              <el-tag :type="getCampaignTypeTag(row.type)">
                {{ getCampaignTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="targetGroup" label="目标分群" min-width="120" />
          <el-table-column prop="startTime" label="开始时间" min-width="100" />
          <el-table-column prop="endTime" label="结束时间" min-width="100" />
          <el-table-column prop="status" label="状态" min-width="80">
            <template #default="{ row }">
              <el-tag :type="getStatusTag(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="效果分析" min-width="220">
            <template #default="{ row }">
              <div class="flex flex-row gap-1">
                <div>发送：{{ row.sentCount }}人</div>
                <div>阅读：{{ row.readCount }}人</div>
                <div>转化：{{ row.conversionRate }}%</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditCampaign(row)">
                编辑
              </el-button>
              <el-button type="success" link @click="handleViewReport(row)">
                报告
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分群表单对话框 -->
      <Drawer
        v-model="showGroupDialog"
        :title="editingGroup.id ? '编辑分群' : '新建分群'"
        size="40%"
        @confirm = "handleConfirmGroup"
      >
        <el-form :model="editingGroup" label-width="100px">
          <el-form-item label="分群名称">
            <el-input v-model="editingGroup.name" placeholder="请输入分群名称" />
          </el-form-item>
          
          <el-form-item label="筛选条件">
            <div class="bg-gray-50 p-4 rounded-lg">
              <div v-for="(condition, index) in editingGroup.conditions" :key="index" class="mb-3">
                <div class="flex items-center gap-2">
                  <el-select v-model="condition.field" placeholder="选择条件" class="w-40">
                    <el-option label="年龄" value="age" />
                    <el-option label="性别" value="gender" />
                    <el-option label="疾病类型" value="disease" />
                    <el-option label="消费金额" value="consumption" />
                    <el-option label="就诊频率" value="visitFrequency" />
                  </el-select>
                  <el-select v-model="condition.operator" placeholder="运算符" class="w-32">
                    <el-option label="等于" value="=" />
                    <el-option label="大于" value=">" />
                    <el-option label="小于" value="<" />
                    <el-option label="包含" value="contains" />
                  </el-select>
                  <el-input v-model="condition.value" placeholder="值" class="w-40" />
                  
                  <el-button type="danger" link @click="removeCondition(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>

              <el-button type="primary" link @click="addCondition">
                <el-icon><Plus /></el-icon>
                添加条件
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </Drawer>

      <!-- 营销活动表单对话框 -->
      <Drawer
        v-model="showCampaignDialog"
        :title="editingCampaign.id ? '编辑活动' : '新建活动'"
        size="600px"
        @confirm = "handleConfirmCampaign"
      >
        <el-form :model="editingCampaign" label-width="100px">
          <el-form-item label="活动名称">
            <el-input v-model="editingCampaign.name" placeholder="请输入活动名称" />
          </el-form-item>
          
          <el-form-item label="活动类型">
            <el-select v-model="editingCampaign.type" placeholder="请选择活动类型" class="w-full">
              <el-option label="健康科普" value="education" />
              <el-option label="优惠活动" value="promotion" />
              <el-option label="专家讲座" value="lecture" />
              <el-option label="回访关怀" value="followup" />
            </el-select>
          </el-form-item>

          <el-form-item label="目标分群">
            <el-select v-model="editingCampaign.targetGroupId" placeholder="请选择目标分群" class="w-full">
              <el-option
                v-for="group in patientGroups"
                :key="group.id"
                :label="group.name"
                :value="group.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="活动时间">
            <el-date-picker
              v-model="campaignTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="w-full"
            />
          </el-form-item>

          <el-form-item label="活动内容">
            <el-input
              v-model="editingCampaign.content"
              type="textarea"
              :rows="4"
              placeholder="请输入活动内容"
            />
          </el-form-item>
        </el-form>
      </Drawer>

      <!-- 活动报告对话框 -->
      <Drawer
        v-model="showReportDialog"
        title="活动效果分析"
        size="800px"
        @confirm = "handleConfirmReport"
      >
        <div class="flex flex-col gap-4">
          <!-- 数据概览 -->
          <div class="grid grid-cols-4 gap-4">
            <div v-for="stat in campaignStats" :key="stat.label" 
              class="bg-gray-50 p-4 rounded-lg text-center"
            >
              <div class="text-gray-500 mb-2">{{ stat.label }}</div>
              <div class="text-xl font-bold" :class="stat.color">
                {{ stat.value }}
              </div>
            </div>
          </div>

          <!-- 趋势图表 -->
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-gray-500 mb-4">响应趋势</div>
            <!-- 这里可以接入图表组件 -->
            <div class="h-64 bg-gray-100 rounded flex items-center justify-center">
              图表区域
            </div>
          </div>

          <!-- 详细数据 -->
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-gray-500 mb-4">患者反馈</div>
            <el-table :data="campaignFeedback" border stripe>
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="patient" label="患者" min-width="100" />
              <el-table-column prop="action" label="动作" width="120" />
              <el-table-column prop="feedback" label="反馈内容" min-width="200" />
            </el-table>
          </div>
        </div>
      </Drawer>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import ElderlyList from '@/components/common/ElderlyList.vue'
import Drawer from '@/components/common/Drawer.vue'

const status = ref('')
const activeView = ref('group')

const getElderlyInfo = (status) => {
  console.log(status)
}

// 患者分群数据
const patientGroups = ref([
  { 
    id: '1', 
    name: '中老年慢性病患者', 
    type: 'warning',
    count: 256,
    conditions: [
      { field: 'age', operator: '>', value: '60' },
      { field: 'disease', operator: 'contains', value: '高血压,糖尿病' }
    ]
  },
  { 
    id: '2', 
    name: '年轻女性', 
    type: 'success',
    count: 189,
    conditions: [
      { field: 'age', operator: '<', value: '35' },
      { field: 'gender', operator: '=', value: '女' }
    ]
  }
])

// 营销活动数据
const marketingCampaigns = ref([
  {
    id: '1',
    name: '夏季养生讲座',
    type: 'lecture',
    targetGroup: '中老年慢性病患者',
    startTime: '2024-07-01',
    endTime: '2024-07-31',
    status: 'active',
    sentCount: 256,
    readCount: 180,
    conversionRate: 45
  },
  {
    id: '2',
    name: '健康体检优惠',
    type: 'promotion',
    targetGroup: '年轻女性',
    startTime: '2024-08-01',
    endTime: '2024-08-31',
    status: 'pending',
    sentCount: 500,
    readCount: 320,
    conversionRate: 35
  }
])

// 分群管理
const showGroupDialog = ref(false)
const editingGroup = ref({
  id: '',
  name: '',
  conditions: []
})
// 分群管理创建
const handleCreate = () => {
  if (activeView.value === 'group') {
    editingGroup.value = {
      id: '',
      name: '',
      conditions: [{ field: '', operator: '', value: '' }]
    }
    showGroupDialog.value = true
  } else {
    editingCampaign.value = {
      id: '',
      name: '',
      type: '',
      targetGroupId: '',
      content: ''
    }
    campaignTimeRange.value = []
    showCampaignDialog.value = true
  }
}
// 分群管理条件标签
const getConditionLabel = (condition) => {
  const fieldLabels = {
    age: '年龄',
    gender: '性别',
    disease: '疾病类型',
    consumption: '消费金额',
    visitFrequency: '就诊频率'
  }
  const operatorLabels = {
    '=': '等于',
    '>': '大于',
    '<': '小于',
    'contains': '包含'
  }
  return `${fieldLabels[condition.field]} ${operatorLabels[condition.operator]} ${condition.value}`
}

// 分群管理添加条件
const addCondition = () => {
  editingGroup.value.conditions.push({ field: '', operator: '', value: '' })
}
// 分群管理删除条件
const removeCondition = (index) => {
  editingGroup.value.conditions.splice(index, 1)
}
// 分群管理编辑
const handleEditGroup = (row) => {
  editingGroup.value = { ...row }
  showGroupDialog.value = true
}
// 分群管理查看成员
const handleViewMembers = (row) => {
  ElMessage.info('查看分群成员：' + row.name)
}
// 分群管理删除
const handleDeleteGroup = (row) => {
  ElMessageBox.confirm('确定要删除该分群吗？', '提示', {
    type: 'warning'
  }).then(() => {
    patientGroups.value = patientGroups.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}
// 分群管理确认
const handleConfirmGroup = () => {
  ElMessage.success('分群已确认')
  showGroupDialog.value = false
}
// 营销活动管理
const showCampaignDialog = ref(false)
const showReportDialog = ref(false)
const editingCampaign = ref({
  id: '',
  name: '',
  type: '',
  targetGroupId: '',
  content: ''
})
const campaignTimeRange = ref([])
// 营销活动类型标签
const getCampaignTypeTag = (type) => {
  const tags = {
    education: 'info',
    promotion: 'success',
    lecture: 'warning',
    followup: 'primary'
  }
  return tags[type]
}
// 营销活动类型标签
const getCampaignTypeLabel = (type) => {
  const labels = {
    education: '健康科普',
    promotion: '优惠活动',
    lecture: '专家讲座',
    followup: '回访关怀'
  }
  return labels[type]
}
// 营销活动类型标签
const getStatusTag = (status) => {
  const tags = {
    active: 'success',
    pending: 'warning',
    ended: 'info'
  }
  return tags[status]
}
// 营销活动状态标签
const getStatusLabel = (status) => {
  const labels = {
    active: '进行中',
    pending: '未开始',
    ended: '已结束'
  }
  return labels[status]
}

// 营销活动编辑
const handleEditCampaign = (row) => {
  editingCampaign.value = { ...row }
  campaignTimeRange.value = [row.startTime, row.endTime]
  showCampaignDialog.value = true
}
// 营销活动确认
const handleConfirmCampaign = () => {
  ElMessage.success('活动已确认')
  showCampaignDialog.value = false
}



// 活动报告数据
const campaignStats = ref([
  { label: '目标人群', value: '256人', color: 'text-blue-500' },
  { label: '到达人数', value: '180人', color: 'text-green-500' },
  { label: '转化人数', value: '45人', color: 'text-orange-500' },
  { label: '投资回报率', value: '168%', color: 'text-red-500' }
])
// 活动报告数据
const campaignFeedback = ref([
  {
    date: '2024-07-01',
    patient: '张三',
    action: '阅读',
    feedback: '内容很实用，希望多举办类似活动'
  },
  {
    date: '2024-07-02',
    patient: '李四',
    action: '报名',
    feedback: '已预约参加讲座'
  }
])
// 活动报告查看
const handleViewReport = (row) => {
  // 这里可以加载具体活动的报告数据
  showReportDialog.value = true
}
// 活动报告确认
const handleConfirmReport = () => {
  ElMessage.success('报告已确认')
  showReportDialog.value = false
}
</script>